import React, { Component } from 'react'
import axios from 'axios'

import store from '../../../redux'
import Api from '../../../config/api'
import Com from '../../../common/common'

import Navbar from '../../../Component/navbar'

import Button from 'antd/lib/button'
import Table from 'antd/lib/table'
import Form from 'antd/lib/form'
import Input from 'antd/lib/input'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import message from 'antd/lib/message'
import DatePicker from 'antd/lib/date-picker'
import Select from 'antd/lib/select'
import Modal from 'antd/lib/modal'

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const FormItem = Form.Item;
const Option = Select.Option;
const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;
const confirm = Modal.confirm;

let oper = null;

const validateNumber = (rule, value, callback) => {
    if (!value) {
        callback()
    }
    else {
        let reg = /^\d*$/g;
        if (reg.test(value)) {
            callback()
        }
        else {
            callback('必须是数字')
        }
    }
}


class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: '',
            endDate: '',
            startMonent: null,
            endMoment: null,
            showAddModal: false,
            sourceSelectData: [{ index: '', desc: '全部' }],
            accountList: []
        }
    }
    componentDidMount() {
        this.getSelect()
    }
    async getSelect() {
        await Com.getSelection.call(this, 'SmsAccountBlacklistSourceEnum', 'sourceSelectData');
        axios.post(Api['getAllUserAccount']).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                this.setState({
                    accountList: data
                }, () => { this.search() })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment
        }
        else {
            return false
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment
        }
        else {
            return false
        }
    }
    search() {
        let obj = {
            account: this.accountInput.input.value,
            phone: this.phoneInput.input.value,
            source: parseInt(this.sourceInput.rcSelect.state.value[0], 10),
            startTime: this.state.startDate,
            endTime: this.state.endDate
        }
        this.props.search(obj, this.state.sourceSelectData)
    }
    addModal() {
        this.setState({
            showAddModal: true
        })
        this.props.form.setFieldsValue({
            account: this.state.accountList[0]
        })
    }
    handleCancel() {
        this.setState({
            showAddModal: false
        })
    }
    handleSure(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                axios.post(Api['addAccountBlacklist'], data).then(res => {
                    if (res) {
                        this.search();
                        this.props.form.resetFields()
                        message.success('提交成功')
                        this.setState({
                            showAddModal: false
                        })
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        return (
            <Navbar ref={(item) => {oper=item}}>
                <Form layout="inline">
                    <FormItem label="账号"><Input style={{ width: '110px' }} ref={(input) => { this.accountInput = input }} /></FormItem>
                    <FormItem label="号码"><Input style={{ width: '110px' }} ref={(input) => { this.phoneInput = input }} /></FormItem>
                    <FormItem label="来源">
                        <Select style={{ width: '120px' }} ref={(input) => { this.sourceInput = input }} defaultValue=''>
                            {this.state.sourceSelectData.map((item, index) => { return <Option key={index} value={item.index}>{item.desc}</Option> })}
                        </Select>
                    </FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="plus" onClick={this.addModal.bind(this)}>添加</Button>
                    </FormItem>
                </Form>
                <Modal visible={this.state.showAddModal} onCancel={this.handleCancel.bind(this)} title="新增" footer={[
                    <Button key="sure" type="primary" onClick={this.handleSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleCancel.bind(this)}>取消</Button>
                ]} >
                    <Form>
                        <FormItem label="账号" {...formItemLayout}>
                            {getFieldDecorator('account', { rules: [{ required: true, message: '必选' }] })(
                                <Select style={{ width: '180px' }}>
                                    {this.state.accountList.map((item, index) => { return <Option key={index} value={item}>{item}</Option> })}
                                </Select>
                            )}
                        </FormItem>
                        <FormItem label="号码" {...formItemLayout}>
                            {getFieldDecorator('phone', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ required: true, message: '请输入号码' }, { len: 11, message: '请输入11位电话号码' }, { validator: validateNumber, message: '纯数字' },Com.validateSpace] })(<Input style={{ width: 180 }} />)}
                        </FormItem>
                    </Form>
                </Modal>
            </Navbar>
        )
    }
}

const ValidateOperbar = Form.create()(OperBar);

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 1,
            tableHeight: 300,
            tableData: this.props.tableData,
            currentPage: 1
        }
    }
    componentDidMount() {
        setTimeout(() => {
            let operbarHeight =  oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
    }
    componentWillReceiveProps(nextProps) {
        this.setState({
            tableData: nextProps.tableData,
            dataNum: nextProps.dataNum,
            currntPage: nextProps.currentPage,
        })
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight =  oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    deleteRow(record) {
        this.props.deleteRow(record)
    }
    render() {
        const columns = [
            { title: '账号', dataIndex: 'account', key: '1', width: '25%' },
            { title: '来源', dataIndex: 'sourceToName', key: '2', width: '15%' },
            { title: '号码', dataIndex: 'phone', key: '3', width: '20%' },
            { title: '创建时间', dataIndex: 'createTime', key: '4', width: '20%' },
            {
                title: '操作',
                key: 'operation',
                width: '20%',
                render: (record) => {
                    return (
                        <div>
                            <a onClick={this.deleteRow.bind(this, record)}>删除</a>
                        </div>
                    )
                }
            },
        ];
        return (
            <div className="common-table">
                <Table title={(data) => { return '账号黑名单' }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ y: this.state.tableHeight }}></Table>
            </div>
        )
    }
}

class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            loading: true,
            tableData: [],
            searchParams: {},
            totalNum: 0,
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            currentPage: 1,
        }
    }
    setParams(obj, sourceSelectData) {
        this.setState({
            searchParams: obj,
            sourceSelectData
        }, () => {
            this.search('btn');
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        axios.post(Api['getAccountBlacklistByParams'], data).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach((item, index) => {
                    item.key = index;
                    item.sourceToName = Com.keyToName(this.state.sourceSelectData, item.source);
                })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag') })
    }
    deleteRow(record) {
        let that = this;
        confirm({
            title: '删除',
            content: '您确定要删除' + record.account + '吗？',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                axios.post(Api['deleteAccountBlacklist'] + '?id=' + record.id).then(res => {
                    if (res) {
                        that.search();
                        message.success('删除成功')
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            },
            onCancel() { },
        });
    }
    render() {
        return (
            <div>
                <ValidateOperbar search={this.setParams.bind(this)} />
                <Spin spinning={this.state.loading} indicator={antIcon}>
                    <Table1 currentPage={this.state.currentPage} tableData={this.state.tableData} dataNum={this.state.totalNum} changePageSize={this.changePageSize.bind(this)} changePage={this.changePage.bind(this)} deleteRow={this.deleteRow.bind(this)} />
                </Spin>
            </div>
        )
    }
}

export default Box